<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" sortable="" />

          <el-table-column label="头像" prop="username" sortable="">
            <template #default="{row}">
              <img v-imgerror="defaultImg" :src="row.staffPhoto" alt="" class="staff" @click="clickShowCodeDialog(row.staffPhoto)"></template>
          </el-table-column>

          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column :formatter="formatEmployment" label="聘用形式" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPermission('del_employee')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog" @add-employee="getEmployeeList" />
    <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    <!-- 分享展示, 预览的二维码的弹层 -->
    <el-dialog title="二维码" :visible="showCodeDialog" @close="closeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees.js'
import addEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import Img from '@/assets/common/head.jpg'
import QrCode from 'qrcode'
import checkPermission from '@/mixins/checkPermission'
export default {
  name: 'Employess',
  components: { addEmployee, AssignRole },
  mixins: [checkPermission],
  data() {
    return {
      page: 1,
      size: 10,
      list: [],
      total: 0,
      loading: false,
      showDialog: false,
      showRoleDialog: false,
      userId: '',
      defaultImg: Img,
      showCodeDialog: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    handleDownload() {
      // 导出员工按钮权限
      if (!this.checkPermission('export-employee')) {
        this.$message.error('上午权限')
        return
      }
      // 懒加载。原因因为这个文件很大，然后导出功能也不是经常使用
      import('@/vendor/Export2Excel').then(async excel => {
        const header = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { data: { rows }} = await reqGetEmployeeList(1, this.total)
        // console.log(rows)
        const data = this.formatJson(rows, header, headersRelations)
        // console.log(data)
        excel.export_json_to_excel({
          header,
          data
        })
      })
    },
    formatJson(rows, header, headersRelations) {
      const resultsArr = []
      rows.forEach(row => {
        const arr = []
        header.forEach(key => {
          const englishKey = headersRelations[key]
          console.log(englishKey)
          const value = row[englishKey]
          arr.push(value)
        })
        resultsArr.push(arr)
        console.log(resultsArr)
      })
      // rows.forEach(row => {
      //   const arr = []
      //   delete row.id
      //   delete row.staffPhoto
      //   delete row.password
      //   for (const key in row) {
      //     console.log(row)
      //     if (row[key] === '') {
      //       console.log(key)
      //     }
      //     arr.push(row[key])
      //   }
      //   // console.log(arr)
      //   resultsArr.push(arr)
      // })
      // // console.log(resultsArr)
      return resultsArr
    },
    // 删除员工
    delEmployee(id) {
      this.$confirm('确定要删除该员工?', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        console.log('取消')
      })
    },
    formatEmployment(row, column, cellValue, index) {
      return EmployeeEnum.hireType.find(item => item.id === +cellValue)?.value || '未知'
    },
    async getEmployeeList() {
      this.loading = true
      const { data } = await reqGetEmployeeList(this.page, this.size)
      this.list = data.rows
      this.total = data.total
      this.loading = false
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    // 生成二维码
    clickShowCodeDialog(url) {
      if (!url) return // 有图片才显示弹层
      this.showCodeDialog = true
      // this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    closeDialog() {
      this.showCodeDialog = false
    }
    // 权限按钮设置
    // checkPermission(key) {
    //   return this.$store.getters.roles?.points.includes(key)
    // }
  }
}
</script>

<style lang="scss" scoped>
.staff{
  width: 70px;
  height: 70px;
  border-radius: 50%;
}
</style>
